#include <iostream>
#include <stdlib.h>
#include <time.h>	
#include "Player.h"

using namespace std;

PlayerImp::PlayerImp(EventProcessor& _master, DistributedCounter& _dCounter)
: dCounter(_dCounter)
#ifdef DEBUG_EVPROC
: EventProcessorImp(true, "Worker") // comment to remove debug
#endif
{
  	Master.CopyFrom(_master);	
  	RegisterMessageProcessor(PlayAgainMessage::type, &Rematch, 1 /*priority*/);
  	RegisterMessageProcessor(DieMessage::type, &Die, 0 /*priority*/);
  	
	SendChoice();	
}

void PlayerImp::SendChoice(){

	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface);
	srand(time(NULL));	
	//srand(1);	
	choice = rand()%3;	
	cout<<"The choice is "<<choice<<endl;
	
	ChoiceMessage_Factory(Master, choice, myInterfClone);
}

MESSAGE_HANDLER_DEFINITION_BEGIN(PlayerImp, Rematch, PlayAgainMessage) 

	cout<<"There was a deadlock !!!"<<endl;
	evProc.SendChoice();	

 
MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(PlayerImp, Die, DieMessage) 

		if(evProc.dCounter.Decrement(1) == 0){
			cout<<"I am the Winner "<<endl;
			EventProcessor myInterfClone;
			myInterfClone.CopyFrom(evProc.myInterface);
			PlayDoneMessage_Factory(evProc.Master, 0, myInterfClone);
			//KillEvProc(evProc.Master);
		}
		else{
			cout<<"I am the loser "<<endl;
		}

	evProc.EventProcessorImp::processDieMessage(evProc,msg);

MESSAGE_HANDLER_DEFINITION_END
